package com.ojoin.ojoin.eb_spider.service.catchdata.suning;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.ojoin.ojoin.eb_spider.service.ISLDataCatchAtomStepService;
import com.ojoin.ojoin.eb_spider.service.SupplyInventoryService;
import com.ojoin.ojoin.eb_spider.service.WebDriverService;
import com.ojoin.ojoin.eb_spider.service.catchdata.SupplierTMALLDataCatchServiceImpl;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.DownloadUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.NumberUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.utils.excel.ExcelReaderUtil;
import com.ojoin.trade.common.utils.excel.IRowReader;
import com.ojoin.trade.common.utils.file.FileUtilsJoin;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlPlatformUser;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyInventory;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyPayment;

@Scope("prototype")
@Service
public class SUNINGInstore implements
		ISLDataCatchAtomStepService<TbSlSupplyInventory> {
	private static Logger log = LoggerFactory
			.getLogger(SUNINGInstore.class);
	@Autowired
	private SupplyInventoryService inventoryService;

	public WebDriverService webDriver;
	public TbSlPlatformUser platformUser;
	public String startTime;
	public String endTime;
	public String downloadDir;

	@Override
	public void get() {
		webDriver
				.get("http://scs.suning.com/sps/PurchaseOrderDelivery/orderDelivery.action");

	}

	@Override
	public void sendKeys() {
		webDriver.sendKeys(WebDriverService.ID, "startReceivedDate", startTime);
		webDriver.sendKeys(WebDriverService.ID, "endReceivedDate", endTime);

	}

	@Override
	public void submit() {
		webDriver
				.click("css",
						"#SearchFrm  table  tbody  tr:nth-child(6)  td:nth-child(1)  a");

	}

	@Override
	public void run() {
		get();
		sendKeys();
		submit();

	}

	/*
	 * @Override public List<TbSlSupplyInventory> result() {
	 * List<TbSlSupplyInventory> purchases = new
	 * ArrayList<TbSlSupplyInventory>();
	 * 
	 * boolean flag = true; // 是否有下一页 while (flag) {
	 * 
	 * // findElement(attribute); WebElement table = webDriver.findElement("id",
	 * "gridTable");
	 * 
	 * List<WebElement> trs = table.findElements(By.tagName("tr"));
	 * Iterator<WebElement> it = trs.iterator(); while (it.hasNext()) {
	 * WebElement tr = it.next();
	 * 
	 * if(webDriver.findElements(tr, "tagName", "td").size() < 1){ continue; }
	 * 
	 * TbSlSupplyInventory payment = this
	 * .getTbSlSupplyInventoryByWebElement(tr); purchases.add(payment); }
	 * 
	 * flag = hasNextPage(); }
	 * 
	 * return purchases; }
	 */

	@Override
	public List<TbSlSupplyInventory> result() throws Exception {
		final List<TbSlSupplyInventory> payments = new ArrayList<TbSlSupplyInventory>();

		Boolean flag = webDriver.IsExist("css", "#foot > ul > li > a");
		if(!flag){
			return payments;
		}
		webDriver.click("css", "#foot > ul > li > a");

		File downloadFileDir = new File(downloadDir);

		IRowReader reader = new IRowReader() {

		public void getRows(int sheetIndex, String sheetName, int curRow,
					List<String> rowlist) {

				if (rowlist.size() != 14) {
					throw new BusinessException("suppReport文件格式出错，不是20行");
				}
				
				if (0 == curRow) {
					return;
				}

				String tid = rowlist.get(0);
				String bid = rowlist.get(1);
				String key = tid + "_" + bid;
				/*
				 * if(set.contains(key)){ return ; }else { set.add(key); }
				 */
				//String fm = "yyyyMMdd";
				//String createDateTime = 
				
				//DateTimeFormatter format = DateTimeFormat.forPattern(fm);

				//DateTime dtcreate = DateTime.parse(createDateTime, format);
				String time =rowlist.get(2);

				String stramount = rowlist.get(11);

				long amount = NumberUtils.getLongAmountRint(stramount);
				
				TbSlSupplyInventory payment = new TbSlSupplyInventory();
				
				payment.setPlatformAccountId(platformUser.getId());
				payment.setItemKey(key);
				payment.setItemId(tid);
				payment.setItemStatus(TbSlSupplyInventory.IN);
				payment.setStoreDate(time);
				payment.setTotalCost(amount);
				
				payments.add(payment);

			}
		};

		FileInputStream in = null;
		File payment = null;
		try {
			payment = DownloadUtils.waitFileDownloadOver(downloadFileDir,
					"^OrderDelivery_.*.csv$");

			LogUtils.info(log, "文件名为：" + payment.getAbsolutePath() + "-->文件大小："
					+ payment.length() / 1024 + "kb");

			in = new FileInputStream(payment);

			ExcelReaderUtil.readCSV(reader, in, "GBK");

			FileUtilsJoin.renameFile(payment, payment.getParent() + File.separator + startTime
					+ "--" + endTime + "in.csv");
			
		} catch (Exception e) {
			throw  e;
		} finally {
			IOUtils.closeQuietly(in);
		}

		return payments;
	}

	public boolean hasNextPage() {

		WebElement ele = webDriver.findElement("css", "#pageFrm div .next");

		if (ele.getTagName().equals("span")) {
			return false;
		} else {
			webDriver.clickByJS(ele);
			return true;
		}

	}

	public void init(WebDriverService webDriver, TbSlPlatformUser platformUser,
			String startTime, String endTime,String downloadDir) {
		this.webDriver = webDriver;

		this.platformUser = platformUser;
		this.startTime = startTime;
		this.endTime = endTime;
		this.downloadDir = downloadDir;

	}

	@Override
	public void fiter(List<TbSlSupplyInventory> list,
			Map<String, TbSlSupplyInventory> map) {
		inventoryService.removeInventoryCommon(list, map);

	}

}
